package kz.kstu.ds.key;

import kz.kstu.ds.entity.User;

import java.io.File;
import java.io.FileOutputStream;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;

/**
 * Date: 04.11.12
 * Time: 20:24
 *
 * @author Oleg Anastassov
 */
public class KeyGenerator {

    public KeyGenerator() {
    }

    public void saveKeys(User u, File f) {
        final String SEPARATOR = "_";
        String userName = u.getSurname() + SEPARATOR + u.getName() + SEPARATOR + u.getPassportNo() + SEPARATOR;
        String publicName = userName + "public.key";
        String privateName = userName + "private.key";

        int keyLength = 1024;
        try {
            KeyPair keyPair = generateKeyPair(keyLength);
            // write the private key
            FileOutputStream output = new FileOutputStream(new File(f, privateName));
            output.write(keyPair.getPrivate().getEncoded());
            output.close();
            // write the public key
            output = new FileOutputStream(new File(f, publicName));
            output.write(keyPair.getPublic().getEncoded());
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public KeyPair generateKeyPair(int keyBitSize) throws GeneralSecurityException {
        // Use a digital signature algorithm generator.
        KeyPairGenerator generator = KeyPairGenerator.getInstance("DSA");
        // Random algorithm is SHA-1 with pseudo-random number generator.
        SecureRandom randomAlg = SecureRandom.getInstance("SHA1PRNG", "SUN");
        randomAlg.setSeed(System.currentTimeMillis());
        generator.initialize(keyBitSize, randomAlg);
        return generator.generateKeyPair();
    }

}
